package com.sy.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Monkey-D-Gu
 * @version 1.0
 * @date 2020/9/11 0011 10:32
 * @usage http相关的工具类方法
 */
public class HttpUtils {
    private HttpUtils() {

    }

    /**
     * 将需要的数据变成JSON字符串形式打印出来
     *
     * @param resp 响应
     * @param obj  需要携带的数据
     * @throws IOException
     */
    public static void writeJson(HttpServletResponse resp, Object obj) throws IOException {
        resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter pw = resp.getWriter();
        pw.print(JSON.toJSONString(obj, true));
    }

    /**
     * 获取Cookie中指定的属性值
     *
     * @param req        请求
     * @param cookieName 需要获取的cookie的名称
     * @return 获取到的Cookie中的值
     */
    public static String getCookie(HttpServletRequest req, String cookieName) {
        Cookie[] cookies = req.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookieName, cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 添加cookie
     * @param resp 响应
     * @param cookieName cookie的名称
     * @param value cookie的值
     * @param storeExpire 保存时间
     */
    public static void setCookie(HttpServletResponse resp,String cookieName,String value,Integer storeExpire) {
        Cookie cookie = new Cookie(cookieName,value);
        cookie.setMaxAge(storeExpire);
        cookie.setPath("/");
        resp.addCookie(cookie);
    }
}
